<template>
  <el-dialog
      v-model="props.updateDialog"
      title="修改工艺路线"
      width="60%"
      :before-close="handleClose"
      align-center
  >
    <div class="process-form">
      <!-- Form Section -->
      <el-form :model="detailsData" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="工艺路线编号">
              <el-input v-model="detailsData.procedureCode" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工艺路线名称">
              <el-input v-model="detailsData.procedureName"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用">
              <el-radio-group v-model="detailsData.isEnabled">
                <el-radio :label="true" value="0">是</el-radio>
                <el-radio :label="false" value="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="工艺路线说明">
          <el-input
              v-model="detailsData.description"
              type="textarea"
              placeholder="请输入内容"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
              v-model="detailsData.remark"
              type="textarea"
              placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>

      <!-- Tabs Section -->
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="组成工序" name="process">
          <div class="table-operations">
            <div>
              <el-button type="primary" plain @click="handleAddProcess" size="small">新增</el-button>
              <el-button type="warning" plain @click="handleEdit" :disabled="select_order_number!=1" size="small">修改
              </el-button>
              <el-button type="danger" plain @click="handleDelete" :disabled="select_order_number==0" size="small">
                删除
              </el-button>
            </div>
            <div>
              <el-button size="small" @click="handleRefresh" :icon="Refresh" circle/>
            </div>
          </div>
          <el-table :data="detailsData.procedureDetails" ref="multipleTable" style="width: 100%" max-height="200px"
                    :header-cell-style="{'text-align':'center','font-size':'13px'}"
                    :cell-style="{'text-align':'center','font-size':'13px'}"
                    @selection-change="handleSelectionChange">
            <el-table-column fixed type="selection" width="55"/>
            <el-table-column fixed label="序号" prop="orderNumber" width="80"/>
            <el-table-column fixed label="工序编码" prop="processCode" width="100"/>
            <el-table-column fixed label="工序名称" prop="processName" width="100"/>
            <el-table-column label="下一道工序" prop="nextProcessName" width="100"/>
            <el-table-column label="与下一道工序关系" prop="nextProcessType" width="150">
              <template #default="scope">
                {{
                  scope.row.nextProcessType === 'FF' ? 'F-to-F' : scope.row.nextProcessType === 'SF' ? 'S-to-F'
                      : scope.row.nextProcessType === 'SS' ? 'S-to-S' : 'F-to-S'
                }}
              </template>
            </el-table-column>
            <el-table-column label="关键工序" prop="isKey">
              <template #default="scope">
                <el-tag :type="scope.row.isKey ==='0' ? 'success' : 'info'" size="small">
                  {{ scope.row.isKey === '0' ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="质检确认" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.isQualitytest ==='0' ? 'success' : 'info'" size="small">
                  {{ scope.row.isQualitytest === '0' ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="准备时间" prop="setupTime"/>
            <el-table-column label="等待时间" prop="latencyTime"/>
            <el-table-column label="甘特图显示颜色" prop="color">
              <template #default="scope">
                <el-color-picker v-model="scope.row.color" show-alpha disabled/>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button type="primary" size="small" link @click="handleEdit(scope.row)">
                  修改
                </el-button>
                <el-button type="danger" size="small" link @click="handleDelete(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="关联产品" name="products">
          <div class="table-operations">
            <div>
              <el-button type="primary" plain @click="handleAddProduct" size="small">新增</el-button>
              <el-button type="warning" plain @click="handleEditProduct" :disabled="select_product_order_number!=1"
                         size="small">修改
              </el-button>
              <el-button type="danger" plain @click="handleDeleteProduct" :disabled="select_product_order_number==0"
                         size="small">删除
              </el-button>
            </div>
          </div>
          <el-table :data="detailsData.procedureProduct" ref="multipleTableProduct" style="width: 100%"
                    max-height="200px"
                    :header-cell-style="{'text-align':'center','font-size':'13px'}"
                    :cell-style="{'text-align':'center','font-size':'13px'}"
                    @selection-change="handleSelectionChangeProduct">
            <el-table-column type="selection" width="55"/>
            <el-table-column label="产品物料编码" prop="productCode"/>
            <el-table-column label="产品物料名称" prop="productName"/>
            <el-table-column label="产品规格型号" prop="specification"/>
            <el-table-column label="产品单位" prop="unit"/>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" size="small" link @click="handleEditProduct(scope.row)">
                  修改
                </el-button>
                <el-button type="danger" size="small" link @click="handleDeleteProduct(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
    <add-process-dialog :addProcessDialog='addProcessDialog' :code='detailsData.procedureCode'
                        :orderNumbers="orderNumber" :processDatas="detailsData.procedureDetails"
                        @close-dialog="close"/>
    <updata-process-dialog :updataProcessDialog='updataProcessDialog' :datas="multipleSelection"
                           :orderNumbers="orderNumber" :processDatas="procedureDetails"
                           @close-dialog="close"/>
    <AddProductDialog :addProductDialog='addProductDialog' :code='detailsData.procedureCode' @close="close"/>
    <UpdataProductDialog v-if="updataProductDialog" :updataProductDialog='updataProductDialog' :procedureDetails="procedureDetails2"
                         :dataCode="props.id" :selectData="multipleSelectionProduct" @close="close"/>
  </el-dialog>
</template>

<script setup>
import {reactive, ref, watch} from 'vue'
import {Refresh} from '@element-plus/icons-vue'
import {deleteDetailsProcess, deleteProduct, findDetails, updateProcess} from "@/apis/zyj/Process.js";
import {ElMessage, ElMessageBox} from "element-plus";
import AddProcessDialog from "@/components/Process/AddProcessDialog.vue";
import UpdataProcessDialog from "@/components/Process/UpdataProcessDialog.vue";
import AddProductDialog from "@/components/Process/AddProductDialog.vue";
import UpdataProductDialog from "@/components/Process/UpdataProductDialog.vue";

const props = defineProps({
  id: String,
  updateDialog: Boolean
})

// Form data
const detailsData = reactive({})
// 已有的工序排序
const orderNumber = ref([])
// 已有的工序
const procedureDetails = ref([])
const procedureDetails2= ref([])

// 监听updateDialog的变化
watch(() => props.updateDialog, async (newValue) => {
  await refresh()
  activeTab.value = 'process'
})

//重新查询数据
const refresh = () => {
  findDetails(props.id).then(res => {
    Object.assign(detailsData, res)
  })
}

const handleRefresh = () => {
  refresh()
}

const addProcessDialog = ref(false)
const updataProcessDialog = ref(false)

const addProductDialog = ref(false)
const updataProductDialog = ref(false)

// Pagination
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 组成工序的多选
const select_order_number = ref('') //表格select选中的条数
const select_orderId = ref([]) //表格select复选框选中的id
const multipleSelection = ref()//选中行的数据
const multipleTable = ref()//用于表格多选框选中的清理
// 产品物料的多选
const select_product_order_number = ref('')//表格select选中的条数
const select_product_orderId = ref([])//表格select复选框选中的id
const multipleSelectionProduct = ref()//选中的行的数据
const multipleTableProduct = ref()//用于表格多选框选中的清理

const emit = defineEmits(['close-dialog'])
// Active tab
const activeTab = ref('process')

const handleClose = () => {
  emit('close-dialog')
}

const handleConfirm = () => {
  // Handle form submission
  updateProcess(detailsData).then(req => {
    if (req === '成功') {
      ElMessage.success('修改成功')
      handleClose()
    } else {
      ElMessage.error('修改失败')
    }
  })
}
//新增工序
const handleAddProcess = () => {
  addProcessDialog.value = true
  //循环找出已有的序号
  orderNumber.value.length = 0
  if (detailsData.procedureDetails != null) {
    for (let i = 0; i < detailsData.procedureDetails.length; i++) {
      orderNumber.value.push(detailsData.procedureDetails[i].orderNumber)
    }
  }
}
//新增产品物料
const handleAddProduct = () => {
  addProductDialog.value = true
}

const handleEdit = (row) => {
  updataProcessDialog.value = true
  if (row.id != null) {
    multipleSelection.value = row
  } else {
    multipleSelection.value = multipleSelection.value[0]
  }
  orderNumber.value.length = 0
  for (let i = 0; i < detailsData.procedureDetails.length; i++) {
    if (multipleSelection.value.id !== detailsData.procedureDetails[i].id) {
      orderNumber.value.push(detailsData.procedureDetails[i].orderNumber)
    }
  }
  procedureDetails.value.length = 0
  for (let i = 0; i < detailsData.procedureDetails.length; i++) {
    if (multipleSelection.value.id !== detailsData.procedureDetails[i].id) {
      procedureDetails.value.push(detailsData.procedureDetails[i])
    }
  }
}

const handleDelete = (row) => {
  if (row.id != null) {
    select_order_number.value = "1";
  } else {
    select_order_number.value = multipleSelection.value.length;
  }
  ElMessageBox.confirm(
      '是否要删除 ' + select_order_number.value + '条数据',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (row.id != null) {
          select_orderId.value = [];
          select_orderId.value.push(row.id)
        }
        deleteDetailsProcess(select_orderId.value).then((res) => {
          if (res == '成功') {
            refresh()
            ElMessage.success('成功删除: ' + select_order_number.value + '条数据')
            select_order_number.value = '0';
            select_orderId.value = [];
            multipleTable.value.clearSelection();
          } else {
            ElMessage.error('系统错误！删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}
//修改产品物料
const handleEditProduct = (row) => {
  updataProductDialog.value = true
  procedureDetails2.value.length = 0
  for (let i of detailsData.procedureDetails) {
    procedureDetails2.value.push(i)
  }
  if (row.id != null) {
    multipleSelectionProduct.value = row
  } else {
    multipleSelectionProduct.value = multipleSelectionProduct.value[0]
  }
  console.log("数据2",multipleSelectionProduct.value,procedureDetails2.value)
}
//删除产品物料
const handleDeleteProduct = (row) => {
  console.log(row)
  if (row.id != null) {
    select_product_order_number.value = "1";
  } else {
    select_product_order_number.value = multipleSelectionProduct.value.length;
  }
  ElMessageBox.confirm(
      '是否要删除 ' + select_product_order_number.value + '条数据',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (row.id != null) {
          select_product_orderId.value = [];
          select_product_orderId.value.push(row.id)
        }
        deleteProduct(select_product_orderId.value).then((res) => {
          if (res == '成功') {
            refresh()
            ElMessage.success('成功删除: ' + select_product_order_number.value + '条数据')
            select_product_order_number.value = '0';
            select_product_orderId.value = [];
            multipleTableProduct.value.clearSelection();
          } else {
            ElMessage.error('系统错误！删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}

const handleSelectionChangeProduct = (val) => {
  multipleSelectionProduct.value = val
  select_product_order_number.value = multipleSelectionProduct.value.length
  select_product_orderId.value = [];
  if (val) {
    val.forEach((row) => {
      if (row) {
        select_product_orderId.value.push(row.id);
      }
    });
  }
  console.log(select_product_orderId.value, multipleSelectionProduct.value)
}

const handleSelectionChange = (val) => {
  // 解决来回切换页面，也无法清除上次选中情况
  multipleSelection.value = val;
  select_order_number.value = multipleSelection.value.length;
  select_orderId.value = [];
  if (val) {
    val.forEach((row) => {
      if (row) {
        select_orderId.value.push(row.id);
      }
    });
  }
}

const handleEditRow = (row) => {
  // Handle row edit
}

const handleDeleteRow = (row) => {
  ElMessage.warning("删除工序")
  // Handle row delete
}
const handleExport = () => {
  console.log("导出")
}

const close = () => {
  addProcessDialog.value = false
  updataProcessDialog.value = false
  addProductDialog.value = false
  updataProductDialog.value = false
  refresh()
}
</script>

<style scoped>
.process-form {
  padding: 20px 0;
}

.table-operations {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total {
  color: #606266;
  font-size: 13px;
}

.page-info {
  color: #606266;
  font-size: 13px;
}

:deep(.el-dialog__body) {
  padding: 0 20px;
}

.dialog-footer {
  padding: 20px 0;
}

.table-operations {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}
</style>